package com.zkyc.framework.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

@Slf4j
public class DecryptDataUtil {
    public static String getDecryptData(String privateKeyStr, String encryptReceiveMsg) {
        String receiveMsg = null;
        try {
            // 把私钥字符串转换成对象
            byte[] privateKeyBy = Base64.getDecoder().decode(privateKeyStr.getBytes());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBy));
            // 同样的，可以固化cipherPrivate ，但是不能固化cipherPrivate，因为它不是线程安全的
            Cipher cipherPrivate = Cipher.getInstance("RSA");
            // 设置为解密模式并设置私钥
            cipherPrivate.init(Cipher.DECRYPT_MODE, privateKey);

            // 进行解密
            byte[] decryptByte = cipherPrivate.doFinal(Base64.getDecoder().decode(encryptReceiveMsg));
            // 转换成字符串
            receiveMsg = new String(decryptByte, "UTF-8");
            log.info("解密后的数据:" + receiveMsg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return receiveMsg;
    }
}
